from __future__ import division
import os , sys

class onlinegraph:
    #import numpy as np
    import matplotlib.pyplot as plt

    def __init__(self,differencesFile,average,saveupto,percentileUsed,
                 companyName,outputFilePNG,graphType,fileWithRawData,
                 figureWidth,figureHeight):
        if figureHeight==0:
            self.figureHeight= 8
        else:
            self.figureHeight=figureHeight
        if figureWidth==0:
            self.figureWidth= 9
        else:
            self.figureWidth=figureWidth
        self.fig = self.plt.figure(1, figsize=(self.figureWidth, self.figureHeight), dpi=100)
        self.fontsize = 0.1 * self.fig.dpi

        self.data={'x':[],'pdf':[],'cdf':[]}
        self.dataflat=[]
        self.differencesFile=differencesFile
        self.average=average
        self.saveupto=saveupto
        self.percentileUsed=percentileUsed
        self.companyName=companyName
        self.outputFilePNG=outputFilePNG
        self.graphType=graphType
        self.fileWithRawData=fileWithRawData
        self.coord={'cdfx':{'xy':(),'xytext':()},
                    'cdfy':{'xy':(),'xytext':()},
                    'mean':{'xy':(),'xytext':()}
                    }
    def getTotalSamlpes(self):
        fileIn=open(self.differencesFile,'r')
        total_samlpes=0
        for text in fileIn:
            row=text.replace('\n','').split(',')
            total_samlpes=total_samlpes+int(row[1])
        return total_samlpes
    def getOptimalHistogramBinSize(self):
        from math import sqrt
        sum=0
        n=len(self.dataflat)
        for sample in self.dataflat:
            sum=sum+sample
        mean=sum/n
        sumdev=0
        for sample in self.dataflat:
            sumdev=sumdev+pow((sample-mean),2)
        var=sumdev/(n-1)
        W=3.49*sqrt(var)*pow(n,-1/3)
        print ('Mean:%s,  Variance:%s, BinSize:%s, Min:%s, Max:%s,n:%s, BinWidth:%s') % (round(mean,2),round(var,2),round(W,2),min(self.dataflat),
                                                                                         max(self.dataflat),n,round((max(self.dataflat)-min(self.dataflat))/W,2))
        return int((max(self.dataflat)-min(self.dataflat))/W)

    def loadBarChartData(self):
        import numpy.numarray as na
        fileIn=open(self.fileWithRawData,'r')
        for text in fileIn:
            row=text.replace('\n','').split(',')
            self.dataflat.append(float(row[0]))
        self.dataflat.sort()

    def loadData(self):
        total_samlpes=self.getTotalSamlpes()
        rowNumber=0
        counter=0
        fileIn=open(self.differencesFile,'r')
        for text in fileIn:
            row=text.replace('\n','').split(',')
            self.data['x'].append(int(row[0]))
            self.data['pdf'].append(round(100*int(row[1])/total_samlpes,2))
            if counter==0:
                self.data['cdf'].append(self.data['pdf'][0])
            else:
                self.data['cdf'].append(self.data['cdf'][counter-1]+self.data['pdf'][counter-1])
            counter=counter+1

    def findCoordinates(self):
        self.coord['cdfx']['xy']=(self.saveupto,self.percentileUsed)
        self.coord['cdfx']['xytext']=(self.getMaxShowedX(),self.percentileUsed)
        self.coord['cdfy']['xy']=(self.saveupto,0)
        self.coord['cdfy']['xytext']=(self.saveupto,self.percentileUsed*1.1)
        self.coord['mean']['xy']=(self.average,0)
        self.coord['mean']['xytext']=(self.average*0.6,self.percentileUsed*0.5)
    def plotAll(self):
        self.create()
    def getMaxShowedX(self):
        return int(self.data['x'][int(len(self.data['x'])*0.95)])
        #return max(self.data['x'])
    def getMinShowedX(self):
        return int(self.data['x'][int(len(self.data['x'])*0.05)])
        #return min(self.data['x'])
    def create(self):
        self.loadBarChartData()
        self.loadData()
        self.findCoordinates()
        ax1 = self.fig.add_subplot(111)
        #ax1.plot(self.data['x'], self.data['pdf'], 'b-')
        ax1.hist(self.dataflat,bins=self.getOptimalHistogramBinSize(), facecolor='purple', alpha=0.3)
        ax2 = ax1.twinx()
        ax2.plot(self.data['x'], self.data['cdf'], 'r-')

        ax2.annotate(('%s %%')%(self.percentileUsed),
                     xy=self.coord['cdfx']['xy'],
                     xytext=self.coord['cdfx']['xytext'],
                     arrowprops=dict(facecolor='purple', shrink=0.05)
                )

        if self.saveupto<0:
            saveUptoMsg='Save up to'
        else:
            saveUptoMsg='Possible loses'
        ax2.annotate(saveUptoMsg,
                     xy=self.coord['cdfy']['xy'],
                     xytext=self.coord['cdfy']['xytext'],
                     arrowprops=dict(facecolor='purple', shrink=0.05)
                )
        
        if self.average<0:
            avgMsg='Avg Savings'
        else:
            avgMsg='Avg Loses'
        ax2.annotate(avgMsg,
                     xy=self.coord['mean']['xy'],
                     xytext=self.coord['mean']['xytext'],
                     arrowprops=dict(facecolor='purple', shrink=0.05)
                )

        ax1.set_xlabel(('Price %s') % self.graphType)
        ax1.set_ylabel('PDF %', color='b')
        ax2.set_ylabel('CDF %', color='r')
        self.plt.title(('%s Price %s density plot')% (self.companyName,self.graphType))
        
        self.plt.xlim(self.getMinShowedX(),self.getMaxShowedX())


        self.fig.text(0.5, 0.1, 'Consumer Intelligence',
             fontsize=50, color='magenta',rotation=40,
             ha='center', va='bottom', alpha=0.05)
        if self.outputFilePNG=="":
            self.plt.show()
        else:
            import Image
            self.plt.savefig(('%s') % self.outputFilePNG)
            Image.open(self.outputFilePNG).save(self.outputFilePNG+'.jpg',quality=90)

if __name__ == "__main__":
    file=str(sys.argv[1])
    average=float(sys.argv[2])
    saveup=float(sys.argv[3])
    saveupPercent=int(sys.argv[4])
    company=str(sys.argv[5])
    outputFilePNG=str(sys.argv[6])
    graphType=str(sys.argv[7])
    fileWithRawData=str(sys.argv[8])
    figureWidth=float(sys.argv[9])
    figureHeight=float(sys.argv[10])

    g=onlinegraph(file,average,saveup,saveupPercent,company,outputFilePNG,graphType,fileWithRawData,figureWidth,figureHeight)
    #g=onlinegraph('c:\\1.csv',-117.10,-209.63,10,'MoneySuperMarket')
    g.plotAll()
